<?php

namespace App\Controllers\User;

use App\Controllers\FrontBase;
use App\Models\UserModel;

class Login extends FrontBase
{
    protected $userModel;
    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    public function index()
    {
        $backurl = $this->request->getGet('backurl');
        $url = isset($backurl) ? urldecode($backurl) : url('user/home/index');

        if (strpos($url, 'login') !== false || strpos($url, 'register') !== false || !$url) {
            $url = url('user/home/index');
        }

        // 判断重复登录
        if ($this->userid) {
            ams_redirect($url);exit();
        }

        if (IS_POST) {
            $post = $this->request->getPost('data');
            ams_clean_xss($post);
            if (!$this->check_captcha('imgcode')) {
                $this->_json(1, '验证码不正确');
            } elseif (empty($post['username']) || empty($post['password'])) {
                $this->_json(1, '账号和密码必须填写');
            }
            $rt = $this->userModel->login($post['username'], $post['password']);
            if ($rt['code'] == 0) {
                set_cookie('userid', $rt['data']['uid'], WEEK);
                // 登录成功
                $this->_json(0, '登录成功', $rt['data']);
            } else {
                $this->_json(1, $rt['msg']);
            }

        }

        $vdata = [
            'meta_title' => '用户登录-首页',
        ];
        return view('user/login.html', $vdata);
    }

    //开放平台登录
    public function oauth()
    {
        # code...
    }

    //退出登录
    public function out()
    {
        $this->userModel->logout();
        $this->msg(0, '您已退出系统', [
            'url' => SITE_URL,
        ]);
    }

    //找回密码
    public function forget()
    {
        $vdata = [
            'meta_title' => '找回密码-用户-首页',
        ];
        return view('user/forget.html', $vdata);
    }

    //后台管理员登录
    public function backend()
    {
        $code = $this->request->getGet('code');
        $code = ams_authcode($code, 'DECODE');
        if (!$code) {
            $this->msg(1, '登录错误1');
        }

        list($userid, $password) = explode('-', $code);

        $admin = $this->session->get('admin_login_user');
        if (!$admin) {
            $this->msg(1, '登录错误2');
        } elseif ($password != md5($admin['username'] . sha1($admin['uid'] . $admin['password']))) {
            $this->msg(1, '登录错误3');
        }

        // 存储状态
        header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
        ams_set_cookie('admin_login_user_ids', $userid . '-' . $admin['uid'], HOUR);
        $this->session->setTempdata('admin_login_user_code', md5($userid . sha1($admin['uid'] . $admin['password'])), HOUR);
        ams_redirect('/user');
        exit();
    }

}
